package com.maya.medicalwastes.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.maya.medicalwastes.entity.SpConfig;
import com.maya.medicalwastes.entity.UpdateInfoEntity;


/**
 * *
 */
public class UpdateUtil {

    public static Boolean isNeedUpdate(int newVersion, Context context) {
        Boolean isNeedUpdate = false;
        int new_version = newVersion; // 最新版本的版本号
        // 获取当前版本号
        int now_version = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            now_version = packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (new_version <= now_version) {
            isNeedUpdate = false;
        } else {
            isNeedUpdate = true;
        }
        return isNeedUpdate;
    }

    public static Boolean isWorkNeedUpdate(UpdateInfoEntity updateInfo, Context context) {
        int newVersion = updateInfo.getVersionCode();
        Boolean isNeedUpdate = false;
        int new_version = newVersion; // 最新版本的版本号
        // 获取当前版本号
        int now_version = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            now_version = packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (new_version <= now_version) {
            isNeedUpdate = false;
        } else {
            String updateWorkType = updateInfo.getUpdateWorkType();
            if (updateWorkType == null || StringUtils.isEmpty(updateWorkType)) {
                isNeedUpdate = true;
            } else {
                isNeedUpdate = isUpdateWorkType(updateWorkType, context);
            }
        }
        return isNeedUpdate;
    }

    private static Boolean isUpdateWorkType(String updateWorkType, Context context) {
        String[] needUpdateWork = updateWorkType.split(",");//服务器上传过来的需要更新的工人id

        String hasWorkTypeStr = PrefUtils.getString(context, SpConfig.WORKER_TYPE, "");
        String[] hasWorkType = hasWorkTypeStr.split(","); //本地存在的str

        //如果从来没打卡过 则都要更新
        if (StringUtils.isEmpty(hasWorkTypeStr)) {
            return true;
        }

        for (String needStr : needUpdateWork) {
            //需要更新的有-1则都要更新
            if ("-1".equalsIgnoreCase(needStr)) {
                return true;
            }

            //有需要更新的工种的就要更新
            for (String hasStr : hasWorkType) {
                if (hasStr.equalsIgnoreCase(needStr)) {
                    return true;
                }
            }
        }

        return false;
    }
}
